//
//  ViewController5.swift
//  networkAndData
//
//  Created by 左忠飞 on 2021/1/14.
//  Copyright © 2021 左忠飞. All rights reserved.
//

import UIKit
import CoreData

class ViewController5: ViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //CoreData
        //获取数据模型文件地址
        let modelUrl = Bundle.main.url(forResource: "Class", withExtension: "momd")
        //创建数据模型管理实例
        let modelManager = NSManagedObjectModel(contentsOf: modelUrl!)
        //创建存储管理实例
        let store = NSPersistentStoreCoordinator(managedObjectModel: modelManager!)
        //设置存储路径
        let path = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! + "/SchoolSQL.sqllite")
        
        print(path)
        
        //设置存储凡是为SQLite
        try! store.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: path, options: nil)
        
        //创建操作数据库上下文实例
        let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        
        //进行存储环境关联
        context.persistentStoreCoordinator = store
        //创建班级数据
        let schoolClass:SchoolClass = NSEntityDescription.insertNewObject(forEntityName: "SchoolClass", into: context) as! SchoolClass
        schoolClass.name = "三年二班"
        schoolClass.studentCount = 60
        
        //创建学生数据
        let student:Student = NSEntityDescription.insertNewObject(forEntityName: "Student", into: context) as! Student
        
        student.name = "张三"
        student.age = 24
        schoolClass.moniter = student
        //进行存储
        if ((try? context.save()) != nil) {
            print("新增成功")
        }
        
        
        //查询
        let request = NSFetchRequest<SchoolClass>(entityName: "SchoolClass")
        //设置查询条件
        request.predicate = NSPredicate(format: "studentCount==60", [])
        //进行查询
        let result:NSAsynchronousFetchResult<SchoolClass> = try! context.execute(request) as! NSAsynchronousFetchResult<SchoolClass>
        
        print(result.finalResult?.first?.name! as Any)
    }
    
    
    override func touchesEstimatedPropertiesUpdated(_ touches: Set<UITouch>) {
        
        
    }
}
